/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.utils;

import java.net.URL;
import java.util.regex.Pattern;
import java.net.MalformedURLException;
import static org.internna.iwebmvc.utils.StringUtils.hasText;

/**
 * Utilities to create and validate URLs.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public final class UrlUtils {

    public static final int HTTP_PORT = 80;
    public static final int HTTPS_PORT = 443;
    public static final Pattern IP_PATTERN = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    public static final Pattern DNS_PATTERN = Pattern.compile("[A-Za-z-]+\\w*(\\.[\\w-]+){0,2}");

    /**
     * Default private constructor for a Utility class.
     */
    private UrlUtils() {
        throw new AssertionError("Do not try to instantiate utility class");
    }

    /**
     * Checks if the string is a valid url by creating a java.net.URL object.
     *
     * @param url any
     * @return true if this conforms the specification
     */
    public static boolean isValidUrl(String urlText) {
        URL url = null;
        try {
            if (hasText(urlText)) {
                url = new URL(urlText);
            }
        } catch (MalformedURLException ex) {
            // So it wan't valid. Nothing to worry about.
        }
        return null != url;
    }

    /**
     * Checks if the provided string is a valid DNS host or IP address.
     *
     * @param host any
     * @return
     */
    public static boolean isValidHost(String host) {
        return hasText(host) ?
            IP_PATTERN.matcher(host).matches() ? true : DNS_PATTERN.matcher(host).matches()
            : false;
    }

    /**
     * Builds a valid Url from its components.
     *
     * @param protocol any
     * @param host any
     * @param port any
     * @param path any
     * @return null unless a correct Url string was found
     */
    public static String buildUrl(String protocol, String host, int port, String path) {
        StringBuilder url = new StringBuilder();
        if (hasText(protocol) && hasText(host)) {
            url.append(protocol).append("://").append(host);
            appendPort(url, port);
            appendPath(url, path);
        }
        return url.length() > 0 ? url.toString() : null;
    }

    protected static void appendPort(StringBuilder builder, int port) {
        if ((port > 0) && (port != HTTP_PORT) && (port != HTTPS_PORT)) {
            builder.append(":").append(port);
        }
    }

    protected static void appendPath(StringBuilder builder, String serverPath) {
        if (hasText(serverPath)) {
            builder.append(serverPath.startsWith("/") ? serverPath : "/" + serverPath);
        }
    }

}
